(function ($) {
    $.stateKeeper = function (options) {
        var _stateKeeper = {
            options: {
                formId:"",
                stateKeepGroups:[
                    {
                        id:"group1-1", //页面中的html标签的id
                        multiSelectAble:false, //是否可以多选
                        itemSelector:""  //jquery的选择器
                    }
                ],
                stateKeepAttrName:"statekeepid", //根据stateKeepGroups中的信息，在所有项目上面保存它的回显唯一标识时使用的属性名称。
                stateKeepInputName:"stateKeep", //用来保存选中项信息的hidden的name属性的值
                stateKeepValSeparator:":", //所有页面中的选中项都被保存为【选中项的唯一标识】【分隔符】【选中项的唯一标识】【分隔符】...的格式，此项配置即用来配置分隔符
                stateKeepItemClassName:null, //选中项的className
                pageHiddenName:"page" //用来存储page信息的hidden的name属性的值
               
            },

            init:function () {
                var options = _stateKeeper.options;
                //config check
                if (options.formId == '') {
                    alert("fromId must be setted");
                    return;
                }
                options.stateKeepItemClassName || alert("stateKeepItemClassName which to highlight is needed");
                //如果formId中不存在name=options.stateKeepInputName的hidden控件，那么就创建一个新的
                //alert( $("#" + options.formId + " :hidden[name=" + options.stateKeepInputName + "]").get(0));
                var $stateKeepValsContainer = $("#" + options.formId + " :hidden[name=" + options.stateKeepInputName + "]");
                $stateKeepValsContainer.get(0) || $("#" + options.formId).append($('<input type="hidden" id="'+options.stateKeepInputName+'" value="" name="'+options.stateKeepInputName+'">'));
                var $stateKeepValsContainer = $("#" + options.formId + " :hidden[name=" + options.stateKeepInputName + "]");
                //alert("form#" + options.formId + " must has a hidden which named " + options.stateKeepInputName);

                for (var i =0 ; i < options.stateKeepGroups.length ; i++) {
                    var group = options.stateKeepGroups[i];
                    $(group.itemSelector).each(function (index) {
                        var stateKeepAttrVal = group.id + "_" + index;
                        $(this).attr(options.stateKeepAttrName, stateKeepAttrVal);
                    //  alert(stateKeepAttrVal);
                    });

                    (function a(group) {
                        $(group.itemSelector).click(function () {

                            var stateKeepVals = $stateKeepValsContainer.val();
                            var keepStateVal = $(this).attr(options.stateKeepAttrName) + options.stateKeepValSeparator;
                            if (group.multiSelectAble) {
                                if (stateKeepVals.indexOf(keepStateVal) < 0) {
                                    $stateKeepValsContainer.val(stateKeepVals + keepStateVal);
                                }
                            } else {
                                if (stateKeepVals.indexOf(keepStateVal) < 0) {
                                    //删除所有同组的选中值
                                    var reg=new RegExp(group.id + "_\\d+:","g");
                                    stateKeepVals = stateKeepVals.replace(reg,"");
                                    $stateKeepValsContainer.val(stateKeepVals + keepStateVal);
                                }
                            }

                            //alert($stateKeepValsContainer.val());
                        })
                    })(group);
                }



                //根据url中参数的信息，生成hidden控件，如果是存储page的控件，那么其值设为1
                var url = window.location.href;
                if (url.indexOf("?") > 0) {
                    var urlArgs = url.substring(url.indexOf("?") + 1, url.length).split("&");
                    //alert(urlArgs);
                    for (var i = 0; i < urlArgs.length; i++) {
                        var argKeyValue = unescape(urlArgs[i]).split("=");
                        var key = argKeyValue[0];
                        var value;
                        if (key == options.pageHiddenName) {
                            value = 1;

                        } else {
                            value = argKeyValue[1];
                        }

                        //防止hidden的value出现undefined
                        if (!value){
                            value = "";
                        }
                        //alert(key + "=" + value);
                        //如果hidden已经存在，那么就直接对他进行赋值，否则创建新的
                        var $inputHidden = $("#" + options.formId + " [name=" + key.replace(/\./g,"\\.") + "]");
                        if ($inputHidden.get(0)) {
                            $inputHidden.val(value);
                        } else {
                            var hiddden = '<input type="hidden" id="'+key+'" value="'+value+'" name="'+key+'">';
                            $("#" + options.formId).append($(hiddden));
                        }
                    }
                }

                //回显配置
                //清除默认的选中项高亮
                for (var i =0 ; i < options.stateKeepGroups.length ; i++){
                    var group = options.stateKeepGroups[i];
                    
                    $(group.itemSelector).removeClass(options.stateKeepItemClassName);

                }

                //根据hidden中的信息进行回显
                var stateKeepValsArray = $stateKeepValsContainer.val().split(options.stateKeepValSeparator);
                for (var i = 0; i < stateKeepValsArray.length; i++) {
                    var stateKeepVal = stateKeepValsArray[i];
                   
                    if (stateKeepVal != "") {
                        var highlightItemSelector = "[" + options.stateKeepAttrName + "=" + stateKeepVal + "]";
                        $(highlightItemSelector).addClass(options.stateKeepItemClassName);
                        
                        if(stateKeepVal.split("_")[1]!=0){
                        	//alert(stateKeepVal+"##");
	                        var text=$("#"+stateKeepVal.split("_")[0]).find("a").eq(stateKeepVal.split("_")[1]).text();
	                     if($("[name='"+stateKeepVal.split("_")[0]+"']").find("label").length>0){
		                         $("[name="+stateKeepVal.split("_")[0]+"]").removeClass("none");
		                         $("[name="+stateKeepVal.split("_")[0]+"]").find("label").text(text);
		                         $(".eliminateCriteria").show();
		                         $(".hasBeenSelected").show();
	                     }
                        }
                        
                        //alert($(highlightItemSelector).attr(options.stateKeepAttrName));
                    }
                }

                //如果信息回显后某个选项组中没有人和选项没选中，那么就把此组的第一个条件项选中
                for (var i =0 ; i < options.stateKeepGroups.length ; i++){
                    var group = options.stateKeepGroups[i];

                    var hasSomeOneSelected = false;
                    $(group.itemSelector).each(function() {
                        if ($(this).hasClass(options.stateKeepItemClassName)) {
                            hasSomeOneSelected = true;
                            return;
                        }
                    });

                    if (!hasSomeOneSelected) {
                        $(group.itemSelector + ":first").addClass(options.stateKeepItemClassName);
                    }

                }


            }
        };

        _stateKeeper.options =  $.extend(_stateKeeper.options, options);

        _stateKeeper.init();

    };

})(jQuery);
